/**
 * Copyright 2013 ABSir's Studio
 * 
 * All right reserved
 *
 * Create on 2013-12-12 下午5:38:07
 */
package com.absir.server.socket;

import java.io.Serializable;
import java.nio.channels.SocketChannel;

import com.absir.context.core.ContextBase;
import com.absir.context.core.ContextUtils;

/**
 * @author absir
 * 
 */
public class SocketChannelContext extends ContextBase {

	/** id */
	private Serializable id;

	/** socketChannel */
	private SocketChannel socketChannel;

	/** attachData */
	private Object attachData;

	/**
	 * @return the id
	 */
	public Serializable getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	protected void setId(Serializable id) {
		this.id = id;
	}

	/**
	 * @return the socketChannel
	 */
	public SocketChannel getSocketChannel() {
		return socketChannel;
	}

	/**
	 * @param socketChannel
	 *            the socketChannel to set
	 */
	public void setSocketChannel(SocketChannel socketChannel) {
		this.socketChannel = socketChannel;
	}

	/**
	 * @return the attachData
	 */
	public Object getAttachData() {
		return attachData;
	}

	/**
	 * @param attachData
	 *            the attachData to set
	 */
	public void setAttachData(Object attachData) {
		this.attachData = attachData;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.absir.appserv.system.context.JContextBase#getLifeTime()
	 */
	@Override
	protected long getLifeTime() {
		return SocketServerContext.ME.getTimeout();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.absir.context.core.ContextBase#stepDone(long)
	 */
	@Override
	public boolean stepDone(long contextTime) {
		boolean stepDone = expirationTime < contextTime;
		if (stepDone && socketChannel != null) {
			retainAt();
			stepDone = false;
			ContextUtils.getThreadPoolExecutor().execute(new Runnable() {

				@Override
				public void run() {
					writeStepDone();
				}
			});
		}

		return stepDone;
	}

	/**
	 * 
	 */
	protected void writeStepDone() {
		InputSocketImpl.writeByteBuffer(socketChannel, SocketServerContext.ME.getBeat());
	}

}
